<?php
namespace Tbf\Bundle\TestBundle\Service;
use Tbf\Component\DateTime\Clock\ChangeableClock;
use Tbf\Component\DateTime\Clock\ClockInterface;
use Tbf\Component\DateTime\DateSequence\DateSequenceInterface;
use Tbf\Component\FileSystem\FileSystemFunction;

/**
 * 持久化的可变时钟
 * 不支持并发!!存在data race!!
 * TODO 使用靠谱的序列化组件...
 */
class PersistChangeableClock extends ChangeableClock
{
    /** @var  ClockInterface */
    protected $cache_path;
    protected $loaded;
    public function __construct($cache_path)
    {
        $this->cache_path = $cache_path;
        $this->loaded = false;
    }
    protected function loadObj()
    {
        if ($this->loaded) {
            return ;
        }
        $this->loaded = true;
        $content = @file_get_contents($this->cache_path);
        if (empty($content)) {
            return;
        }
        $save_obj = unserialize($content);
        foreach (get_object_vars($this) as $key=>$v1) {
            if ($key==='cache_path') {
                continue;
            }
            $this->{$key} = $save_obj->{$key};
        }

        return ;
    }
    protected function saveObj()
    {
        $content = serialize($this);
        FileSystemFunction::putContent($this->cache_path,$content);
    }
    public function now()
    {
        $this->loadObj();
        return parent::now();
    }
    public function setFixTime(\DateTime $time)
    {
        parent::setFixTime($time);
        $this->saveObj();
    }

    public function setOffsetTime(\DateInterval $offset)
    {
        parent::setOffsetTime($offset);
        $this->saveObj();
    }

    public function setSequence(DateSequenceInterface $ds)
    {
        parent::setSequence($ds);
        $this->saveObj();
    }

    protected function nowOnSequence()
    {
        $ret = parent::nowOnSequence();
        $this->saveObj();

        return $ret;
    }
}
